package com.dragee.util;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**带token请求微信服务器
 * @author tys on 9/18/20
 */
@Component
public class HttpTokenUtil {
    // 开发者Id
    private static final String APPID = "wxbec638144b00e6bd";
    // 开发者密钥
    private static final String APPSECRET="6f8304efba6c2a52833a84c7cd61dd96";
    private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?"
            + "grant_type=client_credential&appid=APPID&secret=APPSECRET";


    @Autowired
    private RedisUtil redisUtil;
    /** 获取token 先从redis获取, 获取不到远程获取 然后存到redis
     * @return token
     */
    public String getAuthToken () {
        // 缓存获取 并返回
        String token = redisUtil.get("token");
        if (StrUtil.isNotBlank(token))  return token;

        // 缓存不存在则调用微信服务器, 获取成功放入缓存
        String realurl = ACCESS_TOKEN_URL.replace("APPID", APPID).replace("APPSECRET", APPSECRET);
        HttpResponse resp = HttpUtil.createGet(realurl).execute();
        String result = resp.body();
        if (result.indexOf("errcode") != -1) {
            System.err.println(result);
            return null;
        }
        JSONObject jo = JSONUtil.parseObj(resp.body());
        token = jo.get("access_token").toString();
        redisUtil.set("token", token, Integer.parseInt(jo.get("expires_in").toString()));
        return  token;
    }
}
